/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.munif.util;

import java.io.Serializable;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 *
 * @author Gustavo
 */
public class ConverterGenerico implements Converter, Serializable {

    private Class clazz;

    public ConverterGenerico(Class clazz) {
        this.clazz = clazz;
    }

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        try {
            Object chave = Persistencia.getFieldId(clazz).getType().getConstructor(String.class).newInstance(value);
            return CrudFacade.getInstance().recuperar(clazz, chave);
        } catch (Exception e) {
            new Exception("Problema ao converter objeto" + e);
        }

        return null;
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value != null) {
            Object id = Persistencia.getId(value);
            return id==null?null:String.valueOf(id);
        } else {
            return null;
        }
    }
}
